﻿using System;
using System.Collections.Generic;
using System.Data.Entity.SqlServer;
using System.Web.Http;
using User.Api.Dto.BillOrder;
using User.Api.Helpers;
using System.Linq;
using System.Web.Http.Controllers;
using Common.Logging;
using OutDbContext;
using User.Api.BizExtensions;
using In.Api.Dto.HisWs;
using User.Api.HttpClients;
using System.Net.Http;
using Newtonsoft.Json;
using User.Api.Dto.Bill;

namespace User.Api.Controllers
{
    public class BillOrderController : ApiController
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(BillOrderController));
        private HzfyWeiXinEntities _ctx;

        protected override void Initialize(HttpControllerContext controllerContext)
        {
            _ctx = new HzfyWeiXinEntities();
            base.Initialize(controllerContext);
        }

        protected override void Dispose(bool disposing)
        {
            _ctx.Dispose();
            base.Dispose(disposing);
        }

        /// <summary>
        /// 获取所有缴费订单，只显示取号成功的订单
        /// </summary>
        /// <param name="type">current - 15内订单 history - 历史订单</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetOrderList")]
        public GetOrderListResponse GetOrderList(string type = "current")
        {
            var azUser = AzUser.GetInApi(Request);
            var card = _ctx.HospCard.FirstOrDefault(x => x.WxUserId == azUser.UserId && x.IsDefault == 1);
            if (card == null)
            {
                return new GetOrderListResponse
                {
                    ResultCode = "1",
                    ResultMsg = "找不到就诊卡"
                };
            }
            //List<BillOrder> orders;
            var beginDt="";
            var endDt="";
            if (type == "current")
            {
                beginDt = DateTime.Now.AddDays(-15).ToString("yyyy-MM-dd");
                endDt = DateTime.Now.ToString("yyyy-MM-dd");
                //orders =
                //    _ctx.BillOrder.Where(x => x.CardNo == card.CardNo).IsStatus(BillOrderExtensions.OrderStatus.缴费成功)
                //        .Where(x => SqlFunctions.DateDiff("day", x.CreateTime, DateTime.Today) <= 15)
                //        .OrderByDescending(x => x.OrderDate).ThenByDescending(x => x.CreateTime).ToList();
            }
            else
            {
                beginDt = DateTime.Now.AddYears(-1).ToString("yyyy-MM-dd");
                endDt = DateTime.Now.ToString("yyyy-MM-dd");
                //orders =
                //    _ctx.BillOrder.Where(x => x.CardNo == card.CardNo).IsStatus(BillOrderExtensions.OrderStatus.缴费成功)
                //        .Where(x => SqlFunctions.DateDiff("day", x.CreateTime, DateTime.Today) > 15)
                //        .OrderByDescending(x => x.OrderDate).ThenByDescending(x => x.CreateTime).ToList();
            }

            var request = new Request4GetPayRecords();
            request.CardNo = card.CardNo;
            request.BeginDate = beginDt;
            request.EndDate = endDt;

            Response4GetPayRecords respons;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisNewWs/GetPayRecords", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                respons = responseMsg.Content.ReadAsAsync<Response4GetPayRecords>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内获取历史缴费单出错,信息：{0}", JsonConvert.SerializeObject(ex));

                return new GetOrderListResponse
                {
                    ResultCode = "2",
                    ResultMsg = "获取缴费单列表超时"
                };
            }
            if (respons.ResultCode != "0")
            {
                return new GetOrderListResponse
                {
                    ResultCode = "3",
                    ResultMsg = respons.ResultDesc
                };
            }
            return new GetOrderListResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                //Orders = orders.Select(x => new GetOrderListResponse.Order
                //{
                //    OrderId = x.Id,
                //    OrderNo = x.OrderNo,
                //    CardNo = x.CardNo,
                //    CardName = x.CardName,
                 
                //    OrderDate = x.OrderDate,
                //    OrderDept = x.OrderDept,
                //    FetchTime = x.FetchTime.ToString(),
                //    PrescMoney = x.PrescMoney.GetValueOrDefault().ToString("F2")
                //}).ToList()

                 Orders = respons.RecordList
                .Select(x => new GetOrderListResponse.Order()
                {
                    CardName = card.PatientName,
                    CardNo = card.CardNo,
                    ClinicNo = x.clinicNo,
                    OrderDate = x.orderDate,
                    OrderDept = x.orderDept,
                    FetchTime = x.payDate,
                    TypeId = x.typeId,
                    InvoStatus=x.invoStatus,
                    PrescMoney = x.prescMoney,
                    OrderNo = x.orderNo
                }).ToList()
            };
        }

        /// <summary>
        /// 获取缴费订单详情
        /// </summary>
        /// <param name="orderId">订单Id</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetOrderDetail")]
        public GetOrderDetailResponse GetOrderDetail(string orderNo, string clinicNo, int orderId)
        {
            var azUser = AzUser.GetInApi(Request);
            var card = _ctx.HospCard.FirstOrDefault(x => x.WxUserId == azUser.UserId && x.IsDefault == 1);
            var order = _ctx.BillOrder.IsStatus(BillOrderExtensions.OrderStatus.缴费成功)
                .FirstOrDefault(x => x.CardNo == card.CardNo && x.Id == orderId);
            if (order != null)
            {
                var response1 = new GetOrderDetailResponse
                {
                    ResultCode = "0",
                    ResultMsg = order.Remark ?? "",
                    OrderId = orderId,
                    OrderNo = order.OrderNo,
                    CardNo = order.CardNo,
                    CardName = order.CardName,
                    ClinicNo = order.ClinicNo,
                    PrescMoney = order.PrescMoney.GetValueOrDefault().ToString("F2"),
                    OrderDept = order.OrderDept,
                    OrderDate = order.OrderDate,
                    HasYiBao = order.YiBaoStatus == BillOrderExtensions.YiBaoStatus.使用了医保.ToInt32()
                    && !string.IsNullOrEmpty(order.YiBaoJydjh),
                    Charges = order.YibaoMoney.GetValueOrDefault().ToString("F2"),
                    Cost = order.PersonalMoney.GetValueOrDefault().ToString("F2")
                };

                response1.Items = _ctx.BillOrderItem.Where(x => x.BillOrderId == orderId)
                    .ToList()
                    .Select(x => new GetOrderDetailResponse.BillItem
                    {
                        Account = x.Account,
                        ItemPrice = x.ItemPrice.ToDecimalOrDefault().ToString("F2"),
                        Money = x.Money.ToDecimalOrDefault().ToString("F2"),
                        Name = x.Name,
                        Type = x.Type,
                        Unit = x.Unit
                    }).ToList();

                response1.DisWins = _ctx.BillOrderDisWin.Where(x => x.BillOrderId == orderId).ToList()
                    .Select(x => new GetOrderDetailResponse.DisWinItem
                    {
                        MedicineName = x.MedicineName,
                        VisitNo = x.VisitNo,
                        DisWinAdd = x.DisWinAdd,
                        DisWin = x.DisWin
                    }).ToList();
                return response1;
            }

            //获取院内webservice
            var request = new Request4GetPayRecordsDetail();
            request.PrescNo = clinicNo;
            request.CardNo = card.CardNo;
            request.CardType = card.CardType.ToString();
            request.OrderNo = orderNo; //传订单号
           
            Response4GetPayRecordsDetail respons;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisNewWs/GetPayRecordsDetail", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                respons = responseMsg.Content.ReadAsAsync<Response4GetPayRecordsDetail>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内获取缴费订单详情出错,信息：{0}", JsonConvert.SerializeObject(ex));

                return new GetOrderDetailResponse
                {
                    ResultCode = "2",
                    ResultMsg = "获取缴费单详情超时"
                };
            }
            if (respons.ResultCode != "0")
            {
                return new GetOrderDetailResponse
                {
                    ResultCode = "3",
                    ResultMsg = respons.ResultDesc
                };
            }

            var response = new GetOrderDetailResponse();
            response.VirRcptNo = respons.VirRcptNo;
            response.RealRcptNo = respons.RealRcptNo;
            response.InvoStatus = respons.InvoStatus;
            response.ResultCode = "0";
            response.CardNo = card.CardNo;
            response.CardName = card.PatientName;
            response.ClinicNo = clinicNo;
            response.OrderNo = orderNo;
            response.Items = new List<GetOrderDetailResponse.BillItem>();
            response.DisWins = new List<GetOrderDetailResponse.DisWinItem>();
            foreach (var item in respons.PrescItemList)
            {
                response.Items.Add(new GetOrderDetailResponse.BillItem
                {
                    Account = item.Account,
                    ItemPrice = item.ItemPrice.ToDecimalOrDefault().ToString("F4"),
                    Money = item.Money.ToDecimalOrDefault().ToString("F4"),
                    Name = item.ItemName,
                    Type = item.Type,
                    Unit = item.Unit
                });
            }

            foreach (var item in respons.DisWinList)
            {
                response.DisWins.Add(new GetOrderDetailResponse.DisWinItem
                {
                    MedicineName = item.MedicineName,
                    VisitNo = item.VisitNo,
                    DisWinAdd = item.DisWinAdd,
                    DisWin = item.DisWin
                });
            }
            foreach (var item in respons.CMDisWinList)
            {
                response.DisWins.Add(new GetOrderDetailResponse.DisWinItem
                {
                    MedicineName = item.MedicineName,
                    VisitNo = item.VisitNo,
                    DisWinAdd = item.DisWinAdd,
                    DisWin = item.DisWin
                });
            }
            //foreach (var item in respons.AddressList)
            //{
            //    response.Addresses.Add(new GetOrderDetailResponse.Address
            //    {
            //        ExamId = item.ExamId,
            //        ItemType = item.ExamName,
            //        Location = item.Location,
            //        FetchTime = item.FetchTime
            //    });
            //}

            return response;
        }
    }
}
